package com.hzhc.exception;

import com.hzhc.common.BaseController;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.utils.ResultUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: ExceptionController
 * @Description:
 * @version 1.0
 * @author: duanhm
 * @Date: 2020/03/30 11:15:23
 *
 */
@ControllerAdvice
@Slf4j
@RequiredArgsConstructor
public class ExceptionController extends BaseController implements ErrorController {
	private static final String ERROR_PATH = "/error";

	@SuppressWarnings("unused")
	private ErrorAttributes errorAttributes;

	// @Override
	// public String getErrorPath() {
	// return ERROR_PATH;
	// }

	public ExceptionController(ErrorAttributes errorAttributes) {
		this.errorAttributes = errorAttributes;
	}

	/**
	 * Web页面错误处理
	 */
	@RequestMapping(value = ERROR_PATH, produces = "text/html")
	public String errorPageHandler(HttpServletRequest request, HttpServletResponse response) {
		int status = response.getStatus();
		switch (status) {
		case 403:
			return "error/403";
		case 404:
			return "error/404";
		case 500:
			return "error/500";
		}

		return "index";
	}

	/**
	 * 除Web页面外的错误处理，比如Json/XML等
	 */
	@RequestMapping(value = ERROR_PATH, produces = "Json/XML")
	@ResponseBody
	@ExceptionHandler(value = { Exception.class })
	@SuppressWarnings({ "unused" })
	public ResultUtil<Throwable> errorApiHandler(HttpServletRequest request, final Exception ex, final WebRequest req) {

		RequestAttributes requestAttributes = new ServletRequestAttributes(request);
		log.info(ex.getMessage() + "------------------" + ex.getStackTrace());
		log.error("exception :", ex);
		// Map<String, Object> attr = this.errorAttributes.getErrorAttributes(req,
		// false);
		int status = getStatus(request);
		return ResultUtil.build(ex.getCause(),ResultUtilCodeEnum.DATA_INTERFACE_EXCEPTION);
	}

	private int getStatus(HttpServletRequest request) {
		Integer status = (Integer) request.getAttribute("javax.servlet.error.status_code");
		if (status != null) {
			return status;
		}

		return 500;
	}
}
